package www.bwsensing.com.service.collection.database;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import www.bwsensing.com.common.CollectionService;
import www.bwsensing.com.common.utills.NetworkInterfaceUtil;
import www.bwsensing.com.service.collection.CollectionContainer;
import www.bwsensing.com.service.collection.database.dataobject.ServiceData;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 采集服务
 * @author macos-zyj
 */
@Slf4j
@Service
public class CollectionSetService {
    private static final List<Integer> SERVICE_DATES = new ArrayList<>();

    @Resource
    private ServiceDataMapper serviceDataMapper;
    @Resource
    private CollectionServiceFactory serviceFactory;

    public void checkAndStart(){
        String senderAddress = NetworkInterfaceUtil.getHostIp();
        String hostname = NetworkInterfaceUtil.getHostName();
        List<ServiceData> currentServices = serviceDataMapper.getServiceConfigs(hostname,senderAddress);
        Set<Integer> cacheServices =  new HashSet<>(SERVICE_DATES);
        Set<Integer> currentIds =  new HashSet<>();
        for (ServiceData current : currentServices){
            if(!SERVICE_DATES.contains(current.getId())){
                CollectionService collectionService = serviceFactory.getCollectionService(current);
                current.setService(collectionService);
                SERVICE_DATES.add(current.getId());
                CollectionContainer.startService(current.getId(),current);
            }
            currentIds.add(current.getId());
        }
        cacheServices.removeAll(currentIds);
        for (Integer kid : cacheServices){
            SERVICE_DATES.remove(kid);
            CollectionContainer.stopService(kid);
        }
    }
}
